package com.specialized.auth.customer;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;

import com.rabbitmq.client.Channel;
import com.specialized.common.redis.service.RedisService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
public class SendCodeCustomer {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private RedisService redisService;
    @RabbitListener(queuesToDeclare = @Queue("SEND_CODE"))
    public void sendCodeCustomer(String phonenumber, Message message, Channel channel){
        Long sendCode = redisTemplate.opsForSet().add("SEND_CODE", message.getMessageProperties().getMessageId());
        if(sendCode>0){
            try {
                String url = "https://gyytz.market.alicloudapi.com/sms/smsSend";
                String code = "ab6e8fbcda5b4df89c5a9c7293064b44";
                HashMap map = new HashMap<>();
                map.put("mobile", phonenumber);
                map.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
                map.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
                String codes = RandomUtil.randomNumbers(4);
                System.out.println(codes);
                map.put("param", "**code**:" + codes + ",**minute**:5");
                HttpUtil.createPost(url).header("Authorization", "APPCODE " + code).form(map).execute().body();
                redisService.setCacheObject(phonenumber.toString(),codes.toString(),1L, TimeUnit.MINUTES);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                redisTemplate.opsForSet().remove("SEND_CODE",message.getMessageProperties().getMessageId());
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                throw new RuntimeException(e);
            }
        }

    }
}
